package com.ruoyi.wvp.controller;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.ruoyi.wvp.domain.Surveillance;
import com.ruoyi.wvp.entity.CardReaderImport;
import com.ruoyi.wvp.entity.PushTypeBatchParams;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.wvp.domain.CardReader;
import com.ruoyi.wvp.service.ICardReaderService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.enums.DeletedEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.multipart.MultipartFile;

/**
 * 读卡器Controller
 *
 * @author ruoyi
 * @date 2024-07-29
 */
@RestController
@RequestMapping("/wvp/cardReader")
@Tag(name = "【读卡器】管理")
public class CardReaderController extends BaseController {
    @Autowired
    private ICardReaderService cardReaderService;

    /**
     * 查询读卡器列表
     */
    @Operation(summary = "查询读卡器列表")
    @PreAuthorize("@ss.hasPermi('wvp:cardReader:list')")
    @GetMapping("/list")
    public TableDataInfo list(CardReader cardReader) {
        Page<CardReader> page = getPage();
        cardReaderService.pageList(page, cardReader);
        return getTableDataInfo(page);
    }


    /**
     * 导出读卡器列表
     */
    @Operation(summary = "导出读卡器列表")
    @PreAuthorize("@ss.hasPermi('wvp:cardReader:export')")
    @Log(title = "读卡器", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void exportAll(HttpServletResponse response, CardReader cardReader) {
        List<CardReader> list = cardReaderService.listAll(cardReader);
        list.forEach(item->{
            if(Long.valueOf(0L).equals(item.getDeviceStatus())){
                item.setDeviceStatusStr("离线");
            }else{
                item.setDeviceStatusStr("在线");
            }
            if(Objects.nonNull(item.getUpdateTime())) {
                // 创建一个java.util.Date对象
                Date date = item.getUpdateTime();
                // 将Date转换为Instant
                Instant instant = date.toInstant();
                // 使用ZoneId获取当前系统默认时区
                ZoneId zoneId = ZoneId.systemDefault();
                // 通过Instant和ZoneId转换为LocalDateTime
                LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zoneId);
                item.setEditTime(localDateTime);
            }
        });
        ExcelUtil<CardReader> util = new ExcelUtil<CardReader>(CardReader.class);
        util.exportExcel(response, list, "设备数据");
    }

    /**
     * 获取读卡器详细信息
     */
    @Operation(summary = "获取读卡器详细信息")
    @PreAuthorize("@ss.hasPermi('wvp:cardReader:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(cardReaderService.getById(id));
    }

    /**
     * 新增读卡器
     */
    @Operation(summary = "新增读卡器")
    @PreAuthorize("@ss.hasPermi('wvp:cardReader:add')")
    @Log(title = "读卡器", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CardReader cardReader) {
        cardReader.setDeleted(DeletedEnum.NOMAL.getValue());
        cardReader.setCreateBy(getUsername());
        cardReader.setCreateTime(new Date());
        return toAjax(cardReaderService.save(cardReader));
    }

    /**
     * 修改读卡器
     */
    @Operation(summary = "修改读卡器")
    @PreAuthorize("@ss.hasPermi('wvp:cardReader:edit')")
    @Log(title = "读卡器", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CardReader cardReader) {
        cardReader.setUpdateBy(getUsername());
        cardReader.setUpdateTime(new Date());
        return toAjax(cardReaderService.updateById(cardReader));
    }

    /**
     * 删除读卡器
     */
    @Operation(summary = "删除读卡器")
    @PreAuthorize("@ss.hasPermi('wvp:cardReader:remove')")
    @Log(title = "读卡器", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable(name = "ids") Long[] ids) {
        QueryWrapper<CardReader> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", List.of(ids));
        CardReader cardReader = new CardReader();
        cardReader.setUpdateTime(new Date());
        cardReader.setUpdateBy(getLoginUser().getUser().getUserName());
        cardReader.setDeleted(DeletedEnum.DELETED.getValue());
        return toAjax(cardReaderService.update(cardReader, queryWrapper));
    }


    @Operation(summary = "导入读卡器列表")
    @Log(title = "读卡器管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('wvp:cardReader:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<CardReaderImport> util = new ExcelUtil<CardReaderImport>(CardReaderImport.class);
        List<CardReaderImport> importList = util.importExcel(file.getInputStream());
        List<CardReader> list = new ArrayList<>(importList.size());
        for (CardReaderImport cardReaderImport : importList) {
            CardReader cardReader = new CardReader();
            BeanUtils.copyProperties(cardReaderImport, cardReader);
            list.add(cardReader);
        }
        String operName = getUsername();
        String message = cardReaderService.importCareRedar(list, updateSupport, operName);
        return success(message);
    }

    @Operation(summary = "获取导入读卡器模板")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<CardReader> util = new ExcelUtil<CardReader>(CardReader.class);
        util.importTemplateExcel(response, "读卡器数据");
    }

    @Operation(summary = "修改读卡器")
    @PreAuthorize("@ss.hasPermi('wvp:cardReader:pushType')")
    @Log(title = "读卡器", businessType = BusinessType.UPDATE)
    @PutMapping("/pushType")
    public AjaxResult pushType(@RequestBody CardReader cardReader) {
        cardReader.setUpdateBy(getUsername());
        cardReader.setUpdateTime(new Date());
        return toAjax(cardReaderService.updateById(cardReader));
    }

    @Operation(summary = "批量修改读卡器推送状态")
    @PreAuthorize("@ss.hasPermi('wvp:cardReader:pushTypeBatch')")
    @Log(title = "读卡器", businessType = BusinessType.UPDATE)
    @PostMapping("/pushTypeBatch")
    public AjaxResult pushTypeBatch(@RequestBody PushTypeBatchParams params) {
        CardReader cardReader = new CardReader();
        cardReader.setUpdateBy(getUsername());
        cardReader.setUpdateTime(new Date());
        cardReader.setPushType(params.getPushType());
        Wrapper<CardReader> wrapper= new QueryWrapper<CardReader>()
                .in("id",params.getIds());
        return toAjax(cardReaderService.update(cardReader,wrapper));
    }


}
